package com.ali.config;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.Map;

/**
 * JWT处理工具
 */
@Slf4j
public class JWTUtil {
    private static final String secret = "hello";

    /**
     * 获取Token
     * userName：用户名
     * timeOut：token超时时间，单位为秒
     */
    public static String getToken(String userName, long timeOut) {
        long expireTime = System.currentTimeMillis() + timeOut * 1000;
        Date expireDate = new Date(expireTime);
        log.info("expireDate：" + expireDate);

        Algorithm algorithm = getAlgorithm();

        String token = JWT.create()
                //设置过期时间
                .withExpiresAt(expireDate)
                //设置参数
                .withClaim("username", userName)
                //设置签名
                .sign(algorithm);

        log.info("token：" + token);
        return token;
    }

    /**
     * 获取Algorithm
     */
    private static Algorithm getAlgorithm() {
        return Algorithm.HMAC256(secret);
    }

    /**
     * token验证
     */
    public static Map<String, Claim> tokenVerify(String token) {
        if (!StringUtils.hasLength(token)) {
            throw new RuntimeException("token不能为空");
        }

        Algorithm algorithm = getAlgorithm();

        JWTVerifier jwtVerifier = JWT.require(algorithm).build();
        DecodedJWT decodedJWT = jwtVerifier.verify(token);
        return decodedJWT.getClaims();
    }
}
